package com.sgzn.sgpay.bootstrap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 
 * @author zhongzhongyong
 * @version Id: BootstrapListener.java, v 0.1 2018/4/4 0:20 zhongzhongyong Exp $$
 */
@Slf4j
@WebListener
public final class BootstrapListener implements ServletContextListener {

    public BootstrapListener() {
    }


    private ClassPathXmlApplicationContext context;

    /**
     * Start the service.
     */
    protected void startUp() throws Exception {
        context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext-service-async.xml"});
        context.start();
        context.registerShutdownHook();
        log.info("sgpay-service started successfully");
    }

    /**
     * Stop the service.
     */
    protected void shutDown() throws Exception {
        context.stop();
        log.info("service stopped successfully");
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            startUp();
        } catch (Exception ex) {
            log.error("exception happened while sgpay-service starting : [{}]", ex);
            log.error("ignore interruption ");
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        try {
            shutDown();
        } catch (Exception e) {
            log.error("exception happened while sgpay-service shutdown : [{}]",e);
        }
    }
}
